﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFontDatabase>
#include <QMdiSubWindow>
#include <QFileDialog>
#include <QFileInfo>
#include <QPrinter>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QCloseEvent>
#include <QColorDialog>
#include <QTextList>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
    ui->mdiArea->setBackground(QBrush(Qt::white));
    initFontSize();
    initScroll();
    setWindowAction();
    connect(ui->mdiArea,SIGNAL(subWindowActivated(QMdiSubWindow *)),this,SLOT(setWindowAction()));
    setDocAction(false);

    group=new QActionGroup(this);
    group->setExclusive(true);
    mapper=new QSignalMapper(this);
    connect(ui->menu_3,SIGNAL(aboutToShow()),this,SLOT(addSubWindowAction()));
    connect(mapper,SIGNAL(mapped(QWidget *)),this,SLOT(setActiveSubWindow(QWidget *)));
}

void MainWindow::addSubWindowAction()
{
    QList<QAction*>list=group->actions();
    for(int i=0;i<list.count();i++)
    {
        delete list[i];
    }

    QList<QMdiSubWindow *>subList=ui->mdiArea->subWindowList();
    if(!subList.isEmpty())ui->menu_3->addSeparator();
    for(int i=0;i<subList.count();i++)
    {
        QMdiSubWindow*subwindow=subList[i];
        TextEdit*edit=qobject_cast<TextEdit*>(subwindow->widget());

        QString action_text=QString("%1 %2").arg(i+1).arg(edit->getWindoTitle());
        QAction*action=ui->menu_3->addAction(action_text);
        group->addAction(action);
        action->setCheckable(true);
        if(activeSubWindow()==edit)action->setChecked(true);
        connect(action,SIGNAL(triggered(bool)),mapper,SLOT(map()));
        mapper->setMapping(action,subwindow);
    }

}

void MainWindow::setActiveSubWindow(QWidget *widget)
{
    ui->mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow *>(widget));
}

void MainWindow::initFontSize()
{
    ui->comboBox_size->clear();
    QList<int> list=QFontDatabase::standardSizes();
    for(int val:list)
    {
        ui->comboBox_size->addItem(QString::number(val));
    }


    QFont font=QApplication::font();
    int fontsize=font.pointSize();
    int index=ui->comboBox_size->findText(QString::number(fontsize));
    ui->comboBox_size->setCurrentIndex(index);
}

void MainWindow::initScroll()
{
    ui->mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    ui->mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}

TextEdit *MainWindow::activeSubWindow()
{
    QMdiSubWindow *Window=ui->mdiArea->activeSubWindow();
    if(Window)
    {   
        return  qobject_cast<TextEdit*>(Window->widget());
    }
    else
    {
        return nullptr;
    }
}

QMdiSubWindow *MainWindow::findWindow(const QString &filname)
{
    QString filepath=QFileInfo(filname).canonicalFilePath();
    for(QMdiSubWindow*sub:ui->mdiArea->subWindowList())
    {
        TextEdit*edit=qobject_cast<TextEdit*>(sub->widget());
        if(edit->getDocName()==filepath)
        {
            return sub;
        }
    }
    return nullptr;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    ui->mdiArea->closeAllSubWindows();
    if(ui->mdiArea->currentSubWindow())
    {
        event->ignore();
    }
    else
    {
        event->accept();
    }
}

void MainWindow::setWindowAction()
{
    bool hasWindow=activeSubWindow();
    ui->action_print->setEnabled(hasWindow);
    ui->action_printview->setEnabled(hasWindow);
    ui->action_cut->setEnabled(hasWindow);
    ui->action_redo->setEnabled(hasWindow);
    ui->action_undo->setEnabled(hasWindow);
    ui->action_copy->setEnabled(hasWindow);
    ui->action_paste->setEnabled(hasWindow);
    ui->action_next->setEnabled(hasWindow);
    ui->action_last->setEnabled(hasWindow);
    ui->action_tittle->setEnabled(hasWindow);
    ui->action_cascad->setEnabled(hasWindow);
    ui->action_close->setEnabled(hasWindow);
    ui->action_closeall->setEnabled(hasWindow);
    ui->action_save->setEnabled(hasWindow);
}

void MainWindow::setDocAction(bool b)
{
    ui->action_color->setEnabled(b);
    ui->action_bold->setEnabled(b);
    ui->action_italic->setEnabled(b);
    ui->action_underline->setEnabled(b);
    ui->action_left->setEnabled(b);
    ui->action_center->setEnabled(b);
    ui->action_right->setEnabled(b);
    ui->action_justify->setEnabled(b);

    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        QTextCharFormat format=edit->currentCharFormat();
        ui->action_bold->setChecked(format.font().bold());
        ui->action_italic->setChecked(format.fontItalic());
        ui->action_underline->setChecked(format.fontUnderline());
    }

}


void MainWindow::on_action_new_triggered()
{
    TextEdit*edit=new TextEdit;
    ui->mdiArea->addSubWindow(edit);

    edit->show();
    edit->initNewDoc();
    connect(edit,SIGNAL(copyAvailable(bool)),this,SLOT(setDocAction(bool)));

}

void MainWindow::on_action_open_triggered()
{
    QString filename=QFileDialog::getOpenFileName(this,"打开文件","../","文本文件(*.txt);;所有文件(*.*)");
    if(filename.isEmpty())return;
    if(!filename.isEmpty())
    {
        QMdiSubWindow*sub=findWindow(filename);
        if(sub)
        {
            ui->mdiArea->setActiveSubWindow(sub);
            return;
        }
    }
    TextEdit*edit=new TextEdit;
    ui->mdiArea->addSubWindow(edit);

    if(edit->loadDoc(filename))
    {
        ui->statusbar->showMessage("文件已打开",3000);
        edit->show();
    }
    else
    {
        edit->close();
    }


}

void MainWindow::on_action_save_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        if(edit->saveDoc())
        {
            ui->statusbar->showMessage("文件已保存",3000);
        }

    }
}

void MainWindow::on_action_saveas_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        if(edit->saveAsDoc())
        {
            ui->statusbar->showMessage("文件已保存",3000);
        }

    }
}

void MainWindow::on_action_print_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(!edit)return;
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog dialog(&printer,this);
    //dialog.setOption(QAbstractPrintDialog::PrintSelection);
   // printer.setPrintRange(QPrinter::Selection);
    if(dialog.exec()==QDialog::Accepted)
    {
        edit->print(&printer);
    }

}

void MainWindow::on_action_printview_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(!edit)return;
    QPrinter printer(QPrinter::HighResolution);
    QPrintPreviewDialog dialog(&printer,this);

    connect(&dialog,SIGNAL(paintRequested(QPrinter *)),this,SLOT(printView(QPrinter*)));

    if(dialog.exec()==QDialog::Accepted)
    {
        edit->print(&printer);
    }
}

void MainWindow::printView(QPrinter *printer)
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->print(printer);
    }
}

void MainWindow::on_action_undo_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->undo();
    }
}

void MainWindow::on_action_redo_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->redo();
    }
}

void MainWindow::on_action_cut_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->cut();
    }
}

void MainWindow::on_action_copy_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->copy();
    }
}

void MainWindow::on_action_paste_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->paste();
    }
}

void MainWindow::on_action_close_triggered()
{
    ui->mdiArea->closeActiveSubWindow();
}

void MainWindow::on_action_closeall_triggered()
{
    ui->mdiArea->closeAllSubWindows();
}

void MainWindow::on_action_tittle_triggered()
{
    ui->mdiArea->tileSubWindows();
}

void MainWindow::on_action_cascad_triggered()
{
    ui->mdiArea->cascadeSubWindows();
}

void MainWindow::on_action_next_triggered()
{
    ui->mdiArea->activateNextSubWindow();
}

void MainWindow::on_action_last_triggered()
{
    ui->mdiArea->activatePreviousSubWindow();
}



void MainWindow::on_action_color_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        QColor color=QColorDialog::getColor();
        if(!color.isValid())return;
        QTextCharFormat format;
        format.setForeground(color);
        edit->mergeCurrentCharFormat(format);

        QPixmap pixmap(16,16);
        pixmap.fill(color);
        ui->action_color->setIcon(pixmap);

    }


}

void MainWindow::on_action_bold_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        bool ischeck=ui->action_bold->isChecked();
        QTextCharFormat format;
        format.setFontWeight(ischeck?QFont::Bold:QFont::Normal);
        edit->mergeCurrentCharFormat(format);
    }
}

void MainWindow::on_action_italic_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        bool ischeck=ui->action_italic->isChecked();
        QTextCharFormat format;
        format.setFontItalic(ischeck);
        edit->mergeCurrentCharFormat(format);
    }
}

void MainWindow::on_action_underline_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        bool ischeck=ui->action_underline->isChecked();
        QTextCharFormat format;
        format.setFontUnderline(ischeck);
        edit->mergeCurrentCharFormat(format);
    }
}

void MainWindow::on_action_left_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->setAlignment(Qt::AlignLeft);
    }
}

void MainWindow::on_action_center_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->setAlignment(Qt::AlignCenter);
    }
}

void MainWindow::on_action_right_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->setAlignment(Qt::AlignRight);
    }
}

void MainWindow::on_action_justify_triggered()
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        edit->setAlignment(Qt::AlignJustify);
    }
}

void MainWindow::on_comboBox_symbol_activated(int index)
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        if(index==0)
        {
            QTextCursor cusor=edit->textCursor();
            cusor.beginEditBlock();
            QTextList*list=cusor.currentList();
            if(list)
            {
                list->remove(cusor.block());
                QTextBlockFormat blockFormat=cusor.blockFormat();
                blockFormat.setIndent(0);
                cusor.setBlockFormat(blockFormat);
            }

            cusor.endEditBlock();
            return;
        }
    }

    QTextListFormat::Style style;
    switch(index)
    {
        case 1:
            style=QTextListFormat::ListDisc;
            break;
        case 2:
            style=QTextListFormat::ListCircle;
            break;
        case 3:
            style=QTextListFormat::ListSquare;
            break;
        case 4:
            style=QTextListFormat::ListDecimal;
            break;
        case 5:
            style=QTextListFormat::ListLowerAlpha;
            break;
        case 6:
            style=QTextListFormat::ListUpperAlpha;
            break;
        case 7:
            style=QTextListFormat::ListLowerRoman;
            break;
        case 8:
            style=QTextListFormat::ListUpperRoman;
            break;
        default:
            style=QTextListFormat::ListStyleUndefined;
            break;
    }

    QTextCursor cusor=edit->textCursor();
    cusor.beginEditBlock();
    QTextBlockFormat blockFormat=cusor.blockFormat();
    QTextListFormat listFormat;
    QTextList*list=cusor.currentList();
    if(list)
    {
        //listFormat=list->format();
        list->remove(cusor.block());

        blockFormat.setIndent(0);
        cusor.setBlockFormat(blockFormat);
    }

    listFormat.setStyle(style);
    cusor.createList(listFormat);

    cusor.endEditBlock();
}

void MainWindow::on_fontComboBox_activated(const QString &arg1)
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        QTextCharFormat format;
        format.setFontFamily(arg1);
        edit->mergeCurrentCharFormat(format);
    }


}

void MainWindow::on_comboBox_size_activated(const QString &arg1)
{
    TextEdit*edit=activeSubWindow();
    if(edit)
    {
        QTextCharFormat format;
        format.setFontPointSize(arg1.toInt());
        edit->mergeCurrentCharFormat(format);
    }
}
